package cn.zfgc.jfinal.controller;

import cn.zfgc.base.api.ObjectUtils;
import cn.zfgc.jfinal.core.WebSocketController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;


/**
 * Created by wangwang on 2017/3/6 0006.
 */

@ServerEndpoint("/websocket/test")
public class WebSocketDemoController {
    private static final Logger log = LoggerFactory.getLogger(WebSocketController.class);
    private static final Set<WebSocketDemoController> clientSet = new CopyOnWriteArraySet<WebSocketDemoController>();
    public static int count = 1;
    private Session session;
    private boolean flag = true;

    public WebSocketDemoController() {
    }

    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        clientSet.add(this);
        doSendMessage2Bro();
    }

    @OnClose
    public void onClose(Session var1) {
        flag = false;
        clientSet.remove(this);
    }

    @OnMessage
    public void onMessage(String requestJson, Session session) {
//            session.getBasicRemote().sendText("回复 第" + count++ + "次:" + requestJson);
        doBroadcastMessage(requestJson, session);
    }

    private void doSend(String requestJson, Session session) {
        try {
            session.getBasicRemote().sendText(requestJson);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //广播消息
    private void doBroadcastMessage(String requestJson, Session session) {
        for (WebSocketDemoController client : clientSet) {
            System.out.println((client.session).equals(session));
            Session clientSession = client.session;
            if (!clientSession.equals(session)) {
                doSend(requestJson, clientSession);
            }
        }
    }

    //主动推送消息
    private void doSendMessage2Bro() {
//        flag = false;
        while (flag) {
            for (WebSocketDemoController client : clientSet) {
                try {
                    client.session.getBasicRemote().sendText("主动推送的消息 2s一次");
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
